from flask import Blueprint, jsonify, request
from db import db
from utils.myredis import r
import json

index_blue = Blueprint('index', __name__)


# 获取商家信息
@index_blue.route("/getshops")
def getshops():
    # code = '001'
    # key = "shop"+code
    # # r.removeall_str(key)   # 删除redis信息
    # shop = r.get_str(key)
    # if not shop:
    #     # 并发访问时允许一人访问
    #     res = r.setnx_str(key+'exit', key+'exit')
    #     # print('aaa')
    #     if res:
    #         # print('bbb')
    sql = "select * from shops where code='001'"
    res = db.find(sql)
    return jsonify(res)
    # else:
    #     shop = json.loads(shop)
    # return jsonify({
    #     'code': 200,
    #     'shops': shop,
    # })


# 获取所有分类
@index_blue.route('/getcates')
def getcates():
    cates = r.get_str('cates')
    if not cates:
        sql = "select id,name from category order by sort asc"
        res = db.find_all(sql)
        r.set_str('cates', json.dumps(res))
    else:
        res = json.loads(cates)
    data = []
    if res:
        data = [{
            'id':str(i['id']),
            'text':i['name'],
        } for i in res]
    return jsonify({
        'code': 200,
        'catelist': data,
    })


# 根据分类id获取此分类下的所有商品
@index_blue.route("/getGoodsBycateid")
def getGoodsBycateid():
    # 获取分类id
    cateid = request.args.get('cateid')
    # 获取缓存中此分类下的商品
    goods = r.get_str('goods'+cateid)
    # 如果不存在查询
    if not goods:
        sql="select id,name,price,image,description from dish where category_id=%d and is_deleted=0"%(int(cateid))
        res = db.find_all(sql)
        # 把decimal转成float
        data = [{'id': i['id'], 'name':i['name'], 'price':float(i['price']), 'image':i['image'], 'description':i['description']} for i in res]
        # 加入缓存
        r.set_str('goods'+cateid, json.dumps(data))
    else:
        data = json.loads(goods)
    return jsonify({"code": 200, 'goodslist': data})


# 购物车添加
@index_blue.route('/addcate')
def addcart():
    # 获取参数
    userid = request.args.get('userid')
    gid = request.args.get('gid')
    count = request.args.get('count')
    type = request.args.get('type')
    flavors = request.args.get('flavors')
    # if not all [userid,gid,count,type,flavors]:
    #     return jsonify({'code':400,'msg':'参数错误'})
    # 查询购物车中某个商品是否存在
    pkey = 'cart' + str(userid) + 'goods' + str(gid)
    flag = r.is_exits(pkey)
    if int(flag) == 0:
        # 不存在添加
        r.hash_add(pkey, gid, count)
        r.hash_add(pkey, 'type', type)
        r.hash_add(pkey, 'flavors', json.dumps(flavors))

    else:
        r.hash_hincrby(pkey,gid,count,1)
    # 返回结果
    return jsonify({
        "code": 200,
        "msg": '购买成功'
    })


# 加减
@index_blue.route('/jiajian')
def jiajian():
    # 获取参数
    userid = request.args.get('userid')
    gid = request.args.get('gid')
    count = request.args.get('count')
    type = request.args.get('type')
    # 判断redis是否存在购物车
    key = 'cart' + str(userid) + 'goods' + str(gid)
    res1 = r.is_exits(key)
    print('111',  res1)
    if res1:

        # 存在对count进行增加和减少
        # 1 是减
        if int(type) == 2 and int(count) > 0:
            # 减
            hcount = '-' + count
        else:
            # 2 是加
            hcount = count
        print('333', type)
        res = r.hash_hincrby(key, str(gid), hcount, int(type))
        print('222', res)
        if res == False:
            return jsonify({
                "code": 400,
                "msg": '减的数量必须小于当前买的'
            })
        else:
            return jsonify({
                "code": 200,
                "msg": 'ok'
            })
    else:
        return jsonify({
            "code": 400,
            "msg": '此商品购物车不存在'
        })


from datetime import datetime


# 地址接口
@index_blue.route('/address', methods=['GET', 'POST', 'PUT'])
def address():
    if request.method == 'POST':
        userid = request.args.get('userid')
        data = json.loads(request.data)
        is_default = 0

        if data['isDefault']:
            is_default = 1
        create_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
        update_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
        # %d %s %d %s %s %s %s %s %s %s %s %d %s %s %s %s
        sql = "insert into address_book(user_id,consignee,phone,province_code,province_name,city_code" \
              ",city_name,district_code,district_name,detail,is_default,create_time,update_time,create_user,update_user)" \
              "values (%d,'%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,'%s','%s',%d,%d)"%(int(userid),data['name'],
                                                                                               data['tel'],data['postalCode'],
                                                                                               data['province'],data['areaCode'],data['city'],data['country'],
                                                                                               data['county'],data['addressDetail'],is_default,create_time,update_time,userid,userid)
        db.update(sql)
        db.commit()
        return jsonify({
            "code": 200,
            "msg": '添加成功'
        })
    elif request.method == 'GET':
        userid = request.args.get('userid')
        list = r.get_str('add'+str(userid))
        if not list:
            sql = "select consignee,phone,province_name,city_name,district_name,detail,is_default from address_book where userid=%d"%int(userid)
            res = db.find(sql)
            r.set_str('add'+str(userid),json.dumps(res))
        else:
            res = json.loads(list)

        return jsonify({
            "code": 200,
            "msg": '地址',
            'addlist': res
        })
    else:
        userid = request.args.get('userid')
        try:
            sql1 = "update address_book set is_default=0 where user_id=%d and is_default=1"%int(userid)
            db.update(sql1)
            db.commit()
            sql2 = "update address_book set is_default=1 where id=%d"%int(userid)
            db.update(sql2)
            db.commit()
        except Exception as e:
            print(e)

        return jsonify({
            "code":200,
            'msg':'修改成功'
        })




